  //---- VARIABLES ----//
  var DAY_ID_INDENT = 9;
  var running = false;
  var waiting = false; 
  var startDate; 
  var endDate; 
  var photos;
  //---- END VARIABLES ----//

  function init() {
    // only run loop if it hasn't run this second and isn't running already
    if (running) {
      window.setTimeout(init, 100);
      return true;  
    }
    else if (!waiting) {
      waiting = true;
      window.setTimeout(run, 100);
    }
  }

  function run() {
    called = false;
    waiting = false;
    running = true;
    
    var hour = -1;
    var position = 0;
    var img_col = $('<div />');
    img_col.addClass('picasa-photo-col');
    
    setDates();
    var date = startDate; 
    //var p = response.photos.sort(compareTimestamps);
    for (var i = 0, photo; photo = photos[i]; i++) {
      var photodate = new Date(parseInt(photo['timestamp']));
      if (photodate < date) continue;
      if (photodate > date) date = photodate;
      if (dateDiff(date,endDate) > 1) break;
      if (photodate.getFullYear() == date.getFullYear() &&
          photodate.getMonth() == date.getMonth() &&
          photodate.getDate() == date.getDate()) {

        var img_div;
        var img_a = $('<a />');
        img_a.addClass('picasa-photo-gallery');
        img_a.attr('rel', 'photo_group_' 
          + parseInt((date.getTime()-startDate.getTime())/(24*3600*1000)) 
          + '_' + photodate.getHours());
        img_a.attr('href', photo['urlphoto']);
        img_a.attr('title', photo['desc']);
        if (hour == photodate.getHours())
          img_a.attr('style', 'display:none;');
        else {
          position = photodate.getHours()*60*966/1440;
          img_div = $('<div />');
          img_div.addClass('picasa-photo-icon');
          img_div.attr('style', 'top:'+position+'px;');
          img_div.attr('align', 'right');
          img_col.append(img_div);
        }
        
        var img = $('<img />');
        img.attr('src', photo['urlthumb']);
        img.addClass('picasa-photo');
        
        img_a.append(img);
        img_div.append(img_a);
        
        hour = photodate.getHours();
        
        if (i == photos.length-1 || date.getDate() != new Date(parseInt(photos[i+1]['timestamp'])).getDate()) {
          var colref = "div[id='tgCol" + dateDiff(date,startDate) + "']";
          var col = $(colref).clone(true, true);
          if (col.find("div[class='picasa-photo-col']").length == 0) {
            col.append(img_col);
            $(colref).replaceWith(col);
          }
          img_col = $('<div />');
          img_col.addClass('picasa-photo-col');
        }
      }
    }
    
    $(".picasa-photo-gallery").fancybox({
        'transitionIn'  : 'elastic',
        'transitionOut' : 'elastic',
        'titlePosition'   : 'over',
        'titleFormat'   : function(title, currentArray, currentIndex, currentOpts) {
          return '<span id="fancybox-title-over">Image ' + (currentIndex + 1) + ' / ' + currentArray.length + (title.length ? ' &nbsp; ' + title : '') + '</span>';
        }  
    });

    running  = false;
  }

  //---- HELPER METHODS ----//
  function getDate(date_number) {
    date_number = date_number-32;
    var year = 1970 + parseInt(date_number/512);
    date_number = date_number-(year-1970)*512;
    var month = parseInt(date_number/32);
    date_number = date_number-month*32;
    var day = date_number;
    
    return new Date(year, month, day);
  }
  
  function setDates() {
    var selected_days = [];
    var selected = $("td[class~='dp-weekday-selected']");
    $.each(selected, function(index, value) { 
      selected_days.push(parseInt(value.id.substring(DAY_ID_INDENT))); 
    });
    selected = $("td[class~='dp-weekend-selected']");
    $.each(selected, function(index, value) { 
      selected_days.push(parseInt(value.id.substring(DAY_ID_INDENT))); 
    });
    selected_days.sort();
    
    startDate = getDate(selected_days[0]);
    endDate = getDate(selected_days[selected_days.length-1]);
  }
  
  function compareTimestamps(a, b) {
    return parseInt(a['timestamp']) - parseInt(b['timestamp']);
  }
  
  function dateDiff(a, b) {
    return parseInt((a.getTime()-b.getTime())/(24*3600*1000));
  }
  //---- END HELPER METHODS ----//

  function reload(user) {
    chrome.extension.sendRequest({action: 'reload', user: user}, function(response) {});
  };

  chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
    if (request.action == "rewrite") {
      $("div[class='picasa-photo-col']").remove();
      getPhotos();
      init();
    }
  });

  function getPhotos() {
    chrome.extension.sendRequest({action: 'photos'}, function(response) {
      photos = response.photos.sort(compareTimestamps);
    });
  }

  // RUN PHOTOS INITIALIZATION
  getPhotos();
  
  // LISTENERS
  $("#gbg").ready(function() {
    var user = $("#gbi4t").text();
    reload(user);
  });  
  
  $(document).ready(function() {
    $("#calcontent").bind("DOMSubtreeModified", function() {
      init();
    });
  });

